
const superagent = require('superagent');
const fs = require("fs");
const path = require("path");
const utils = require('./utils');
const config = require('./config');

let dirPkgPath;
const type = config.type;
const appShFileName = "install_app_pkg.sh";
const siotShFileName = "install_sdk_pkg.sh";
let appPkgFileName = "";
let appZsyncFileName = "";
let siotPkgFileName = "";
let lastSuccessfulBuild = "";
const pxLastBuildPkgDownloadUrl = config.pxLastBuildPkgDownloadUrl
const siotLastBuildPkgDownloadUrl = config.siotLastBuildPkgDownloadUrl

let needDownload = false;



getInfos()
const timer = setInterval(() => {
  getInfos()
}, 300000);


async function getInfos () {
  needDownload = false;
  appPkgFileName = "";
  siotPkgFileName = "";
  lastSuccessfulBuild = "";
  let state = await requestBuildData();
  // if (state) state = await downloadApp();
  // if (state) state = await downloadAppPkg();
  // if (state) state = await downloadSiot();
  // if (state) state = await downloadSiotPkg();
  if (state) state = await utils.execShell(appShFileName, appPkgFileName, siotShFileName, siotPkgFileName, lastSuccessfulBuild);
}

async function requestBuildData () {

  const result = await superagent
    .get(config.buildStateUrl)
    .then(resp => resp.body)
    .catch(e => {
      return null;
    })
  if (result) {
    //最后一次成功构建版本
    lastSuccessfulBuild = result.lastSuccessfulBuild.number;
    //最后一次构建版本
    let lastBuild = result.lastBuild.number;
    //当前版本
    let currentBuild = utils.getCurrentBuild();
    console.log("当前版本:", currentBuild);
    if (currentBuild) {
      //存储过版本号
      if (currentBuild == lastBuild) {
        //没有最新的构建
        console.log("app没有最新的构建包。");
        console.log(" ")

      } else if (currentBuild == lastSuccessfulBuild) {
        //最新的构建没有成功
        console.log("app最新的构建没有成功，不更新。");
        console.log(" ")
      } else if (lastBuild == lastSuccessfulBuild) {
        //最新的构建成功，下载安装 
        console.log("app最新的构建包有更新，开始准备下载安装。版本号（" + lastSuccessfulBuild + ")");
        console.log(" ")
        needDownload = true;

      } else {
        console.log("当前版本:", currentBuild);
        console.log("最后一次构建版本:", lastBuild);
        console.log("最后一次成功构建版本:", lastSuccessfulBuild);
      }
    } else {
      //没有存储过版本号，重新下载安装。 
      needDownload = true;
      console.log("未查询到初始构建版本号，开始安装。版本号（" + lastSuccessfulBuild + ")");
      console.log(" ")
    }
    if (needDownload) {
      console.log("开始下载资源。");
      console.log(" ")
      dirPkgPath = path.join(__dirname, "pkg");
      if (!fs.existsSync(dirPkgPath)) {
        fs.mkdirSync(dirPkgPath);
      }
      return true;
    }
  } else {
    console.log("app获取最新的构建版本失败了:" + config.buildStateUrl);
  }
  return true;
}

async function downloadApp () {
  console.log("开始下载:", appShFileName);
  let stream = fs.createWriteStream(path.join(dirPkgPath, appShFileName));
  const result = await superagent
    .get(pxLastBuildPkgDownloadUrl + appShFileName)
    .then(resp => resp.body)
    .catch(e => {
      return null;
    })
  if (result) {
    fs.createWriteStream('/home/respeaker/check_px_build1/pkg/' + appShFileName)
    fs.writeFile("/home/respeaker/check_px_build1/pkg/" + appShFileName, result, "binary", function (err) {
      if (err) throw err;
    });
    console.log(appShFileName + ":下载成功");
    console.log(" ")
    return true;
  } else {
    await utils.sendState(appShFileName + ":下载失败", lastSuccessfulBuild)
    console.log(appShFileName + ":下载失败");
    await utils.sendState(appShFileName + ":下载失败", lastSuccessfulBuild)
  }
  return false;
}

function getAppPkg (artifacts, type) {
  for (var i in artifacts) {
    if (artifacts[i].fileName.indexOf(type) > -1 && artifacts[i].fileName.indexOf(".tar.gz") > -1 && artifacts[i].fileName.indexOf(".symbols.tar.gz") == -1) {
      return artifacts[i].fileName;
    }
  }

}

async function downloadAppPkg () {
  const result = await superagent
    .get(config.appPkgInfoUrl)
    .then(resp => resp.body)
    .catch(e => {
      return null;
    })
  if (result) {
    if (type == "M1") {
      appPkgFileName = getAppPkg(result.artifacts, "M1")
      appZsyncFileName = utils.getAppPkgZsync(result.artifacts, "M1")
    } else {
      appPkgFileName = getAppPkg(result.artifacts, "M2")
      appZsyncFileName = utils.getAppPkgZsync(result.artifacts, "M2")
    }
    utils.setZsyncUrl(appZsyncFileName)
    console.log("开始下载:", appPkgFileName);

    let stream = fs.createWriteStream(path.join(dirPkgPath, appPkgFileName));
    const data = await superagent
      .get(pxLastBuildPkgDownloadUrl + appPkgFileName)
      .type('blob')
      .then(resp => resp.body)
      .catch(e => {
        return null;
      })
    if (data) {
      fs.createWriteStream('/home/respeaker/check_px_build1/pkg/' + appPkgFileName)
      fs.writeFile("/home/respeaker/check_px_build1/pkg/" + appPkgFileName, data, "binary", function (err) {
        if (err) throw err;
      });
      console.log(appPkgFileName + ":下载成功");
      console.log(" ")
      return true;
    } else {
      await utils.sendState(appPkgFileName + ":下载失败", lastSuccessfulBuild)
      console.log(appPkgFileName + ":下载失败");
    }
  } else {
    console.log("获取最新的构建版本包名称失败");
  }
  return false;

}



function getSiotPkg (artifacts, type) {
  for (let i in artifacts) {
    if (artifacts[i].fileName.indexOf(type) > -1 && artifacts[i].fileName.indexOf(".tar.gz") > -1 && artifacts[i].fileName.indexOf(".symbols.tar.gz") == -1) {
      return artifacts[i].fileName;
    }
  }
}

async function downloadSiotPkg () {
  const result = await superagent
    .get(config.siotPkgInfoUrl)
    .then(resp => resp.body)
    .catch(e => {
      return null;
    })
  if (result) {
    if (type == "M1") {
      siotPkgFileName = getSiotPkg(result.artifacts, "arm-linux")
    } else {
      siotPkgFileName = getSiotPkg(result.artifacts, "aarch64-linux")
    }
    console.log("开始下载:", siotPkgFileName);
  } else {
    await utils.sendState(config.siotPkgInfoUrl + ":下载失败", lastSuccessfulBuild)
    console.log(config.siotPkgInfoUrl + ":下载失败");
  }

  if (result) {

    let stream = fs.createWriteStream(path.join(dirPkgPath, siotPkgFileName));
    const data = await superagent
      .get(siotLastBuildPkgDownloadUrl + siotPkgFileName)
      .then(resp => resp.body)
      .catch(e => {
        return null;
      })
    if (data) {
      fs.createWriteStream('/home/respeaker/check_px_build1/pkg/' + siotPkgFileName)
      fs.writeFile("/home/respeaker/check_px_build1/pkg/" + siotPkgFileName, data, "binary", function (err) {
        if (err) throw err;
      });
      console.log(siotPkgFileName + ":下载成功");
      console.log(" ")
      return true;

    } else {
      await utils.sendState(siotPkgFileName + ":下载失败", lastSuccessfulBuild)
      console.log(siotPkgFileName + ":下载失败");
    }
  } else {
    console.log("获取最新的构建版本包名称失败");
  }
  return false;
}

async function downloadSiot () {
  let stream = fs.createWriteStream(path.join(dirPkgPath, siotShFileName));
  console.log("开始下载:", siotShFileName);
  const result = await superagent
    .get(siotLastBuildPkgDownloadUrl + siotShFileName)
    .then(resp => resp.body)
    .catch(e => {
      return null;
    })

  if (result) {
    fs.createWriteStream('/home/respeaker/check_px_build1/pkg/' + siotShFileName)
    fs.writeFile("/home/respeaker/check_px_build1/pkg/" + siotShFileName, result, "binary", function (err) {
      if (err) throw err;
    });
    console.log(siotShFileName + ":下载成功");
    console.log(" ")
    return true;
  } else {

    await utils.sendState(siotShFileName + ":下载失败", lastSuccessfulBuild)
    console.log(siotShFileName + ":下载失败");
  }
  return false;
}
